<!--
 表格封装
 管理数据的增删改

-->
<template>
<div class="tabWarp" >
 
    
    <!--删除确认提示框-->
    <Modal v-model="isShowDelModel" width="360">
        <p slot="header" style="color:#f60;text-align:center">
            <Icon type="ios-information-circle"></Icon>
            <span>删除确认</span>
        </p>
        <div style="text-align:center">
            <p>删除后数据不可恢复,</p>
            <p>是否继续删除</p>
        </div>
        <div slot="footer">
            <Button type="error" size="large" long :loading="delLoadingStataus" @click="doDel">Delete</Button>
        </div>
    </Modal>
    <!--定义顶部工具栏-->
    <div class="toolbar">
        <!--查询面板-->
         <div class="search-con">
           <!-- <Form  inline class="search-con" :label-width="60" >
                <template   v-for="(item, index) in searchColumns" >
                    <FormItem   :key="index" :label="item.title">
                       <Input  class="item" type="text" size="small" v-model="item.value" :placeholder="item.placeholder" :key="index" />
                  </FormItem>
                </template>
             </Form>  -->
              <template  v-for="(item, index) in searchColumns"  >
                <Input  clearable :prefix="item.prefix" :suffix="item.suffix" class="item" type="text" size="small" v-model="item.value" :placeholder="item.placeholder" :key="index" />
              </template>
            </div>

         <ButtonGroup class="rightButs" >
              <Button icon="md-settings" size="small"  v-if="buttons.indexOf('hidel',0)>=0" title="隐藏列"></Button>
              <Button icon="ios-construct" size="small" v-if="buttons.indexOf('filtr',0)>=0" title="过虑"></Button>
              <Button icon="md-trash" @click="onBatchDelClick" v-if="buttons.indexOf('del',0)>=0" type="error" size="small" title="删除"></Button>
              <Button icon="md-add"   @click="onAddClick" v-if="buttons.indexOf('add',0)>=0" type="success" size="small" title="添加"></Button>
             
              <!-- <Button icon="ios-stats" size="small" title="统计"></Button>
              <Button icon="md-cloud-download" size="small" title="下载"></Button> -->
        
              <!-- <Button  size="small">
                <Dropdown placement="bottom-start">
                    <a href="javascript:void(0)">
                        更多操作
                        <Icon type="ios-arrow-down"></Icon>
                    </a>
                    <DropdownMenu slot="list">
                        <DropdownItem>驴打滚</DropdownItem>
                        <DropdownItem>炸酱面</DropdownItem>
                        <DropdownItem>豆汁儿</DropdownItem>
                        <DropdownItem>冰糖葫芦</DropdownItem>
                        <DropdownItem>北京烤鸭</DropdownItem>
                      </DropdownMenu>
                </Dropdown>
              </Button> -->
              
          </ButtonGroup>
    
    </div>

    
    <Table
      class="table"
      ref="tablesMain"
      :data="insideTableData"
      :columns="insideColumns"
      :stripe="stripe"
      :border="border"
      :show-header="showHeader"
      :width="width"
      :height="height"
      :loading="loading"
      :disabled-hover="disabledHover"
      :highlight-row="highlightRow"
      :row-class-name="rowClassName"
      :size="size"
      :no-data-text="noDataText"
      :no-filtered-data-text="noFilteredDataText"
      @on-current-change="onCurrentChange"
      @on-select="onSelect"
      @on-select-cancel="onSelectCancel"
      @on-select-all="onSelectAll"
      @on-selection-change="onSelectionChange"
      @on-sort-change="onSortChange"
      @on-filter-change="onFilterChange"
      @on-row-click="onRowClick"
      @on-row-dblclick="onRowDblclick"
      @on-expand="onExpand"
    >
      <slot name="header" slot="header"></slot>
      <slot name="footer" slot="footer"></slot>
      <slot name="loading" slot="loading"></slot>
    </Table>
   

  </div>
</template>

<script>
let moment = require("moment");
import TablesEdit from './edit.vue'
import handleBtns from './handle-btns'
import './index.less'
export default {
  name: 'Tables',
  props: {
    value: {
      type: Array,
      default () {
        return []
      }
    },
    columns: {
      type: Array,
      default () {
        return []
      }
    },
    size:{
        type:String,
        default:"small"
    },
    width: {
      type: [Number, String]
    },
    height: {
      type: [Number, String]
    },
    showHeader: {
      type: Boolean,
      default: true
    },
    highlightRow: {
      type: Boolean,
      default: false
    },
   
    context: {
      type: Object
    },
    /**
     * 表格配制
     */
    tableCofig:{
      type:Object
    },
    /**
     * 查询字段
     */
    searchColumns:{
        type:Array,
        default(){
          return []
        }
    },
    loadDataApi:{
      type:Function,
      default(){
        console.error("请设置加载涵数 loadDataApi")
      }
    },
    editDataApi:{
       type:Function,
        default(){
          console.error("请设置编辑涵数 editDataApi")
        }
    },
    delDataApi:{
       type:Function,
        default(){
          console.error("请设置删除涵数 delDataApi")
        }
    }
  },
  /**
   * Events
   * @on-start-edit 返回值 {Object} ：同iview中render函数中的params对象 { row, index, column }
   * @on-cancel-edit 返回值 {Object} 同上
   * @on-save-edit 返回值 {Object} ：除上面三个参数外，还有一个value: 修改后的数据
   */
  data () {
    return {
      delLoadingStataus:false,
      currentDelRow:null,
      isShowDelModel:false,
      searchParams:[],
      insideColumns: [],
      insideTableData: [],
      edittingCellId: '',
      edittingText: '',
      searchValue: '',
      loading:true,//开启加载提示
      editable:false,//全局设置是否可编辑
      disabledHover:false,//禁用鼠标悬停时的高亮
      noFilteredDataText:'没有查到你要的数据哦',//筛选数据为空时显示的提示内容
      noDataText:'暂无数据',
      rowClassName:function(row,index){
          
        },//行样式
      buttons:["filtr",'del','add','hidel'],  
      border:false,//显示表格线
      stripe:false,//斑马纹
    }
  },
  created(){
      this.loadData();
     
  },
  methods: {
   
    loadData(){
        this.loading=true;
        this.loadDataApi()
        .then(res=>{
            this.loading=false;
            this.insideTableData=res.data.records?res.data.records:res.data;
        })
        .catch(err=>{
           this.loading=false;
           this.$Message.error(err);
        })
    },
    suportEdit (item, index) {
      item.render = (h, params) => {
        return h(TablesEdit, {
          props: {
            params: params,
            value: this.insideTableData[params.index][params.column.key],
            edittingCellId: this.edittingCellId,
            editable: this.editable
          },
          on: {
            'input': val => {
              this.edittingText = val
            },
            'on-start-edit': (params) => {
              this.edittingCellId = `editting-${params.index}-${params.column.key}`
              this.$emit('on-start-edit', params)
            },
            'on-cancel-edit': (params) => {
              this.edittingCellId = ''
              this.$emit('on-cancel-edit', params)
            },
            'on-save-edit': (params) => {
              this.value[params.row.initRowIndex][params.column.key] = this.edittingText
              this.$emit('input', this.value)
              this.$emit('on-save-edit', Object.assign(params, {value: this.edittingText}))
              this.edittingCellId = ''
            }
          }
        })
      }
      return item
    },
    surportHandle (item) {
      let options = item.options || []
      let insideBtns = []
      options.forEach(item => {
        if (handleBtns[item]) insideBtns.push(handleBtns[item])
      })
      let btns = item.button ? [].concat(insideBtns, item.button) : insideBtns
      item.render = (h, params) => {
        params.tableData = this.value
        return h('div', btns.map(item => item(h, params, this)))
      }
      return item
    },
    /**
     * 过虑隐藏的列
     */
    filtrColumns(columns){
        var newsColumns=[];
        columns.forEach(v=>{
          if(!v.hidel){
            newsColumns.push(v)
                 
          }
        });
        return newsColumns;
    },
    /**
     * 初始化操作列
     */
    initColumnsAction(){
      
      if(this.tableCofig.action){
        let actionColumn={
            title: this.tableCofig.action.title?this.tableCofig.action.title:'操作',
            key: 'action',
            width: this.tableCofig.action.width?this.tableCofig.action.width:200,
            align: 'center',
            render: (h, params) => {
                return h('div',this.generateActionButs(h,params));
          }
        }
        this.insideColumns.push(actionColumn);
      }
     
    },
    /**
     * 生成操作按钮
     */
    generateActionButs(h,params){
        let functions=[];
        if(this.tableCofig.action.buttons){
             this.tableCofig.action.buttons.forEach(v=>{
            var but= h('Button', {
                      props: {type: v.type?v.type:'primary',size: 'small'},
                      style: {marginRight: '5px'},
                      on: {
                          click: () => {
                              v.action(params)
                          }
                      }
                  }, v.title);
            functions.push(but);
          })
        }
       
        if(this.tableCofig.action.showDel){
          functions.push(
                h('Button', {
                    props: {type: 'success',size: 'small'},
                    style: {marginRight: '5px'},
                    on: {
                          click: () => {
                            this.onEdit(params)
                        }
                    }
                  }, '编辑'));
        }
        if(this.tableCofig.action.showEdit){
           functions.push( 
                h('Button', {
                      props: {type: 'error',size: 'small'},
                      style: {marginRight: '5px'},
                      on: {
                          click: () => {
                              this.onDelClick(params)
                          }
                      }
                  }, '删除'))
        }
      
        return functions;
    },
    handleColumns (columns) {
      this.insideColumns = columns.map((item, index) => {
        if(item.id){
          this.idKey=item.key;
        }
        let res = item
        if (res.editable) res = this.suportEdit(res, index)
        if (res.key === 'handle') res = this.surportHandle(res)
        /**
         * 数据格式化
         */
        if(res.format){
           switch(res.format){
               case 'date':
                res.render=this.dateFormatRender
                break
           }
        }
        return res
      })
    },
  
    handleClear (e) {
      if (e.target.value === '') this.insideTableData = this.value
    },
    handleTableData () {
     
      this.insideTableData = this.value.map((item, index) => {
        let res = item
        res.initRowIndex = index
        return res
      })
    },
    doDel(){
        if(this.currentDelRow==null){
            console.error("兄台你人才啊!你咋触发这个操作的请告知")
            return;
        }
      
        if(this.tableCofig.idKey||this.idKey){
            this.delLoadingStataus=true;
            this.delDataApi(this.currentDelRow[this.idKey?this.idKey:this.tableCofig.idKey])
            .then(res=>{
                this.delLoadingStataus=false;
                this.currentDelRow=null;
                this.isShowDelModel=false;
                this.loadData()
            })
            .catch(err=>{
                this.delLoadingStataus=false;
                this.currentDelRow=null;
                this.$Message.error(err);
            }) 
        }else{
          console.error("开发前请祥看文档,idKey没配啊");
        }
    },
    onDelClick(params){
      this.currentDelRow=params.row;
      this.isShowDelModel=true;
    },
    /**
     * 批量删除
     */
    onBatchDelClick(){

    },
    onEdit(params){
      this.$emit('onEdit',params);
    },
    onAddClick(){
        this.$emit('onAdd',{});
    },
    exportCsv (params) {
      this.$refs.tablesMain.exportCsv(params)
    },
    clearCurrentRow () {
      this.$refs.talbesMain.clearCurrentRow()
    },
    onCurrentChange (currentRow, oldCurrentRow) {
      this.$emit('on-current-change', currentRow, oldCurrentRow)
    },
    onSelect (selection, row) {
      this.$emit('on-select', selection, row)
    },
    onSelectCancel (selection, row) {
      this.$emit('on-select-cancel', selection, row)
    },
    onSelectAll (selection) {
      this.$emit('on-select-all', selection)
    },
    onSelectionChange (selection) {
      this.$emit('on-selection-change', selection)
    },
    onSortChange (column, key, order) {
      this.$emit('on-sort-change', column, key, order)
    },
    onFilterChange (row) {
      this.$emit('on-filter-change', row)
    },
    onRowClick (row, index) {
      this.$emit('on-row-click', row, index)
    },
    onRowDblclick (row, index) {
      this.$emit('on-row-dblclick', row, index)
    },
    onExpand (row, status) {
      this.$emit('on-expand', row, status)
    },

    /**
     * 时间格式化
     */
    dateFormatRender(h,params){
        let time=new Date(params.row[params.column.key]);
        debugger;
        return h('span',{
           props:{}
        },moment(time).format("YYYY/MM/DD HH:mm"))
    }
  },
  watch: {
    columns (columns) {
      this.handleColumns(this.filtrColumns(columns))
    },
    value (val) {
      this.handleTableData()
  
    }
  },
  mounted () {
    //复制对像参数
    let newObj =Object.assign(this.$data,{},this.tableCofig)
    this.searchColumns.forEach(v=>{
        v.value=null
      
    })
    this.handleColumns(this.filtrColumns(this.columns))
    this.initColumnsAction()
    this.handleTableData()
  }
}
</script>
